package com.tanhua.server.service;

import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.dubbo.api.SoundApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Sound;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.SoundVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class SoundService {
    @DubboReference
    private SoundApi soundApi;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //投放漂流瓶
    public void saveSound(MultipartFile soundFile) throws IOException {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //判断语音是否已存在
        if(soundFile.isEmpty()){
            throw new BusinessException(ErrorResult.error());
        }
        //上传视频到FastDFS中
        StorePath storePath = this.client.uploadFile(soundFile.getInputStream(), //获取输入流
                soundFile.getSize(),  //获取长度
                StrUtil.subAfter(soundFile.getOriginalFilename(), '.', true),
                null);
        //构建Sound对象
        Sound sound=new Sound();
        sound.setUserId(userId);
        //获取路径 并且拼接
        sound.setSouUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());
        //调用api,保存数据
        String soundId=soundApi.saveSound(sound);
        if(soundId==null){
            throw new BusinessException(ErrorResult.error());
        }
    }
    //获取漂流瓶
    public SoundVo getSound() {

        //获取当前id
        Long userId = UserHolder.getUserId();
        //获取漂流瓶集合
        List<Sound> soundList=soundApi.getSound();
        Random rand = new Random();
        Sound randomSound=new Sound();
        int a=100;
        //循环100次
        while (a!=0) {
            randomSound = soundList.get(rand.nextInt(soundList.size()));
            //判断是不是自己的漂流瓶
            if(randomSound.getUserId()!=userId){
                //不是,结束循环
                break;
            }
            a--;
        }
        //循环100次后,如果还是失败,报异常
        if(randomSound==null||randomSound.getUserId()==userId){
            throw new BusinessException(ErrorResult.error());
        }
        //获取当前漂流瓶的用户详情
        UserInfo userInfo = userInfoApi.findById(randomSound.getUserId());
        //转化为vo
        SoundVo vo = SoundVo.init(userInfo, randomSound);
        //当天所剩次数
        //获取当天时间
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        //查看redis是否存在
        String redisKey= date+UserHolder.getUserId();
        String redisValue=redisTemplate.opsForValue().get(redisKey);
        //判断redisValue是否存在
        if(redisValue==null){
            //如果不存在,set一个
            redisTemplate.opsForValue().set(redisKey,"1");
            //赋值给vo
            vo.setRemainingTimes(10-1);
        }else {
            //有值并且有次数,先删掉原有的数据
            redisTemplate.delete(redisKey);
            //重新赋值,value+1
            redisTemplate.opsForValue().set(redisKey,Integer.parseInt(redisValue)+1+"");
            //赋值给vo
            vo.setRemainingTimes(10-Integer.parseInt(redisValue)-1);
        }
        soundApi.delete(randomSound.getId());
        return vo;
    }
}
